package core

import (
	"fmt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/websocket"
	"sync"
	"time"
)

var (
	ws              *websocket.Server
	socketMutex     sync.Mutex
	currentClientId string
)

func setupWebsocket(app *iris.Application) {
	// create our echo websocket server
	ws = websocket.New(websocket.Config{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	})
	ws.OnConnection(handleConnection)
	// 注册客户端（浏览器）连接服务器的url地址
	app.Get("/echo", ws.Handler())
	// serve the javascript built'n client-side library,
	// see websockets.html script tags, this path is used.
	app.Any("/iris-ws.js", func(ctx iris.Context) {
		ctx.Write(websocket.ClientSource)
	})
}

/**
设计一个前后端通信管道，目标当前上下文一个。
*/
func handleConnection(c websocket.Connection) {
	// Read events from browser
	Logger().Debugf("连接启动：clientid：", c.ID())
	c.On("chat", func(msg string) {
		// Print the message to the console, c.Context() is the iris's http context.
		fmt.Printf("%s sent: %s\n", c.Context().RemoteAddr(), msg)
		//原路返回消息
		c.Emit("chat", msg)
		//广播给除当前客户端之外的所有客户端
		//c.To(websocket.Broadcast).Emit("console", msg)
	})
	c.OnPing(func() {
		Logger().Debugf("连接心跳：clientid:%s time:%s", c.ID(), time.Now().Format("2018-08-15 12:24:25"))
	})
}

func resetWebSocket(c websocket.Connection)  {
	socketMutex.Lock()
	defer socketMutex.Unlock()
	var err error
	if len(currentClientId) > 0 {
		err = ws.Disconnect(currentClientId)
		if err != nil {
			Logger().Error("closeWebSocket:"+currentClientId, err)
		}
	}
	if c!=nil {
		currentClientId = c.ID()
	}
}

func closeWebSocket() {
	resetWebSocket(nil)
}
